package com.elock.intf.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.dao.impl.DaoCenter;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.ExceptionUtil;
import com.elock.entity.Car;

/**
 * Dao - 车辆
 * @author 仁德
 */
@Repository("intfCarDao")
public class IntfCarDao extends DaoCenter {

	public Page<Map<String, Object>> findPage(Pageable pageable, Object[] args) {

		List<Object> list = new ArrayList<Object>();

		String companyCode = (String) args[0];
		String carNumber = (String) args[1];
		String carType = (String) args[2];
		String saleOrgSn = (String) args[3];

		StringBuilder sql = new StringBuilder();
		sql.append("select c.*,so.name sale_org_name from car c");
		sql.append(" left join company_info ci on ci.id=c.company_info_id");
		sql.append(" left join car_sale_org cso on c.id=cso.car");
		sql.append(" left join sale_org so on so.id=cso.sale_org where 1=1");

		if (companyCode != null) {
			sql.append(" and ci.company_code=?");
			list.add(companyCode);
		}
		if (!ConvertUtil.isEmpty(carNumber)) {
			sql.append(" and c.car_number like ?");
			list.add("%" + carNumber + "%");
		}
		if (!ConvertUtil.isEmpty(carType)) {
			sql.append(" and c.car_type like ?");
			list.add("%" + carType + "%");
		}
		if (!ConvertUtil.isEmpty(saleOrgSn)) {
			sql.append(" and so.sn=?");
			list.add(saleOrgSn);
		}

		sql.append(" order by c.create_date desc");

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}

		Page<Map<String, Object>> getPage = getNativeDao().findPageMap(sql.toString(),
				objs,
				pageable);

		return getPage;

	}

	public Car findByCarNumber(String carNumber) {

		if (ConvertUtil.isEmpty(carNumber)) {
			ExceptionUtil.throwDaoException("value is empty!");
		}
		String sql = "select * from car where car_number = ?";
		Car car = getNativeDao().findSingleManaged(sql,
				new Object[] { carNumber },
				Car.class);
		return car;
	}
}